package com.qf.weekexam.interceptor;
import com.qf.weekexam.entity.User;
import com.qf.weekexam.service.UserService;
import com.qf.weekexam.utils.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
@Slf4j
public class Myinterceptor implements HandlerInterceptor {

    @Autowired
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        //1. 如果用户已经登录过，session中已经保存了用户的登录状态，这时如果再访问 /login.html ，直接重定向到 /plateform.html
        final HttpSession session = request.getSession();
        final Object sessionUser = session.getAttribute(Constants.USER_SESSION_KEY);


        if (sessionUser!=null){
            log.debug("用户已经登录过了，sesesion中有user对象，直接重定向到/plateform.html");
            response.sendRedirect("/plateform.html");

            return false; // 本次请求处理完毕，到此打住，不再往后面的handler或者静态资源页面进行转发了
        }

        //获取cookie数组从浏览器
        final Cookie[] cookies = request.getCookies();

        //将session加入到浏览器
        //HttpSession session = request.getSession();

        if (cookies == null) {
            return true;
        } else {
            //遍历cookies，判断是否存在免登录的cookie
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(Constants.USER_COOKIE_KEY)) {
                    String value = cookie.getValue();
                    String[] split = value.split("/");
                    User user = userService.login(split[0], split[1]);
                    if (user != null) {
                        session.setAttribute(Constants.USER_SESSION_KEY, user);
                        response.sendRedirect("/plateform.html");
                        return false;
                    }
                }
            }
            return true;
        }

    }

}
